#coding=utf8
import cv2
import os
import numpy as np
import  time

'''
合并本地的4路视频为一个画面(画中画)
只要本地的视频是同步的，合并后也是同步的。

'''

cap1 = cv2.VideoCapture('D:\\data\\1.mp4')
cap2 = cv2.VideoCapture('D:\\data\\2.mp4')
cap3 = cv2.VideoCapture('D:\\data\\3.mp4')
cap4 = cv2.VideoCapture('D:\\data\\4.mp4')

# 调用cv2方法获取cap的视频帧（帧：每秒多少张图片）
print ("%s %s %s %s" % (cap1.get(cv2.CAP_PROP_FPS), cap2.get(cv2.CAP_PROP_FPS), cap3.get(cv2.CAP_PROP_FPS), cap4.get(cv2.CAP_PROP_FPS)))
# 统一设置fps,  4个值不一致，而且每次的情况还不一样 25.0 25.0 180000.0 25.0
fps = 25.0
print(fps) # 25.0

# 合成
size = (int(cap1.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(cap1.get(cv2.CAP_PROP_FRAME_HEIGHT)))
#resize
size2 = (int(cap1.get(cv2.CAP_PROP_FRAME_WIDTH) / 2),
        int(cap1.get(cv2.CAP_PROP_FRAME_HEIGHT) / 2))
print("%s  %s" %( size,size2  ) ) # (1920, 1080)

#windows支持的格式
fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')

merge_path  = "D:\\data\\merge-local-4.mp4"
if os.path.exists(merge_path):
    os.remove(merge_path)
merge_video = cv2.VideoWriter(merge_path, fourcc, fps, size)


def exit():
    cap1.release()
    cap2.release()
    cap3.release()
    cap4.release()
    merge_video.release()
    cv2.destroyAllWindows()

def read_save():
    # 获取视频流打开状态
    if cap1.isOpened():
        rval = cap1.grab()
        index = cap1.get(cv2.CAP_PROP_POS_FRAMES)  # 视频文件的当前位置（以毫秒为单位）或视频捕获时间戳。  CAP_PROP_POS_MSEC
        print("1: index=%s   result=%s  " % (index, rval))

    if cap2.isOpened():
        rval2 = cap2.grab()
        index2 = cap2.get(cv2.CAP_PROP_POS_FRAMES)
        print("2: index=%s   result=%s  " % (index2, rval2))

    if cap3.isOpened():
        rval3 = cap3.grab()
        index3 = cap3.get(cv2.CAP_PROP_POS_FRAMES)
        print("3: index=%s   result=%s  " % (index3, rval3))

    if cap4.isOpened():
        rval4 = cap4.grab()
        index4 = cap4.get(cv2.CAP_PROP_POS_FRAMES)
        print("4: index=%s   result=%s  " % (index4, rval4))

    if rval:
        frame = cap1.retrieve()
    if rval2:
        frame2 = cap2.retrieve()
    if rval3:
        frame3 = cap3.retrieve()
    if rval4:
        frame4 = cap4.retrieve()

    if rval and rval2 and rval3 and rval4:
        im1 = cv2.resize(frame[1], size2)
        im2 = cv2.resize(frame2[1], size2)
        hmerge1 = np.hstack((im1, im2))  # 水平拼接

        im3 = cv2.resize(frame3[1], size2)
        im4 = cv2.resize(frame4[1], size2)
        hmerge2 = np.hstack((im3, im4))  # 水平拼接

        merge = np.vstack( (hmerge1,hmerge2 ))

        merge_video.write(merge) #写文件
        #cv2.imshow('test', merge)# 显示

        return  True
    # 都返回false，说明读完了
    if not rval and not rval2 and  not rval3 and not rval4:
        return  False

while True:
    try:
        # esc 退出
        if cv2.waitKey(1) & 0xFF == 27:
            exit()
            break
        if not read_save():
            break
    except Exception,ee:
        print(ee)



